package com.iwayin.core.utils.imagesearch;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author LIUWENLONG https://datamarket.azure.com/account/keys
 *         lwlnuligongzuo@hotmail.com nuligongzuo
 */
public class BImageSearch {
	private final static String accountKey = "oYLa+Pqxsb8/16HsPJIk+qjAQnWcm+9CijW9ucMKIko=";

	public static List<ImageDO> search(ImageDO query) {
		try {
			StringBuffer imageSearchUrl = new StringBuffer("https://api.datamarket.azure.com/Bing/Search/Image?$format=json");
			String encoderQueryKey = URLEncoder.encode(query.getImageSearchKey(), "utf-8");
			imageSearchUrl.append("&Query=").append("%27").append(encoderQueryKey).append("%27");
			imageSearchUrl.append("&$top=").append(query.getPerPageSize());
			imageSearchUrl.append("&$skip=").append(query.getStartRow());
			byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
			String accountKeyEnc = new String(accountKeyBytes);

			HttpClient tbClient = new HttpClient();
			PostMethod method = new PostMethod(imageSearchUrl.toString());
			method.addRequestHeader("Authorization", "Basic " + accountKeyEnc);
			tbClient.executeMethod(method);
			String response = method.getResponseBodyAsString();
			return BImageSearch.response2Image(response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static List<ImageDO> response2Image(String response) {
		List<ImageDO> imageList = new ArrayList<ImageDO>();
		try {
			JSONObject result = new JSONObject(response);
			JSONArray images = result.getJSONObject("d").getJSONArray("results");
			int end = images.length();
			for (int i = 0; i < end; i++) {
				JSONObject image = images.getJSONObject(i);
				String title = image.getString("Title");
				String mediaUrl = image.getString("MediaUrl");
				String sourceUrl = image.getString("SourceUrl");
				String displayUrl = image.getString("DisplayUrl");
				String width = image.getString("Width");
				String height = image.getString("Height");
				String fileSize = image.getString("FileSize");
				String contentType = image.getString("MediaUrl");
				String thumbnailUrl = image.getJSONObject("Thumbnail").getString("MediaUrl");

				ImageDO img = new ImageDO();
				img.setTitle(title);
				img.setWidth(width);
				img.setHeight(height);
				img.setFileSize(fileSize);

				img.setSourceUrl(sourceUrl);
				img.setMediaUrl(mediaUrl);
				img.setDisplayUrl(displayUrl);
				img.setThumbnailUrl(thumbnailUrl);

				img.setContentType(contentType);
				imageList.add(img);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return imageList;
	}
	
	public static void main(String[] args) {
		// ImageDO query = new ImageDO();
		// query.setImageSearchKey("林志玲");
		// BImageSearch.search(query);
		// String response =
		// "{\"d\":{\"results\":[{\"__metadata\":{\"uri\":\"https://api.datamarket.azure.com/Data.ashx/Bing/Search/Image?Query=\u0027林志玲\u0027&$skip=0&$top=1\",\"type\":\"ImageResult\"},\"ID\":\"e935772e-888d-4829-8964-2ed90d8ea998\",\"Title\":\"林志玲\",\"MediaUrl\":\"http://orzz.cc/img/photo/1/1150.jpg\",\"SourceUrl\":\"http://orzz.cc/fullsize/kristin_kreuk_wallpaper/1/1150\",\"DisplayUrl\":\"orzz.cc/fullsize/kristin_kreuk_wallpaper/1/1150\",\"Width\":\"854\",\"Height\":\"1192\",\"FileSize\":\"99944\",\"ContentType\":\"image/jpeg\",\"Thumbnail\":{\"__metadata\":{\"type\":\"Bing.Thumbnail\"},\"MediaUrl\":\"http://ts4.mm.bing.net/images/thumbnail.aspx?q=4822755017753107&id=41ad3d37445bd125a91933b7036ff60e\",\"ContentType\":\"image/jpg\",\"Width\":\"114\",\"Height\":\"160\",\"FileSize\":\"4033\"}},{\"__metadata\":{\"uri\":\"https://api.datamarket.azure.com/Data.ashx/Bing/Search/Image?Query=\u0027林志玲\u0027&$skip=1&$top=1\",\"type\":\"ImageResult\"},\"ID\":\"1ca476c2-6676-4316-a97f-4a90b3e84c16\",\"Title\":\"林志玲否認邱士楷有十億身家：我們不會結婚--娛樂 ...\",\"MediaUrl\":\"http://big5.china.com/gate/big5/images2.china.com/fun/zh_cn/star/news/11052670/20110916/16768775_2011091609212881860700.jpg\",\"SourceUrl\":\"http://big5.china.com/gate/big5/ent.china.com/star/news/11052670/20110916/16768775.html\",\"DisplayUrl\":\"big5.china.com/gate/big5/ent.china.com/star/news/11052670/20110916...\",\"Width\":\"311\",\"Height\":\"444\",\"FileSize\":\"39414\",\"ContentType\":\"image/jpeg\",\"Thumbnail\":{\"__metadata\":{\"type\":\"Bing.Thumbnail\"},\"MediaUrl\":\"http://ts1.mm.bing.net/images/thumbnail.aspx?q=4991804892775696&id=2b7f7b0f6fbeb6e55af4ca7bd0f0b575\",\"ContentType\":\"image/jpg\",\"Width\":\"112\",\"Height\":\"160\",\"FileSize\":\"3989\"}},{\"__metadata\":{\"uri\":\"https://api.datamarket.azure.com/Data.ashx/Bing/Search/Image?Query=\u0027林志玲\u0027&$skip=2&$top=1\",\"type\":\"ImageResult\"},\"ID\":\"a8e2fd55-e9a4-49d8-8f57-5cd0d437b170\",\"Title\":\"林志玲 遠東國際飯店 - 林志玲 遠東國際飯店 - 美女 ...\",\"MediaUrl\":\"http://www.orzzm.com/img/1/523-2.jpg\",\"SourceUrl\":\"http://orzzm.com/image/1/523\",\"DisplayUrl\":\"orzzm.com/image/1/523\",\"Width\":\"600\",\"Height\":\"900\",\"FileSize\":\"128957\",\"ContentType\":\"image/jpeg\",\"Thumbnail\":{\"__metadata\":{\"type\":\"Bing.Thumbnail\"},\"MediaUrl\":\"http://ts1.mm.bing.net/images/thumbnail.aspx?q=4742013920215464&id=ba422db291b4dfe6c01245c111eb50b2\",\"ContentType\":\"image/jpg\",\"Width\":\"106\",\"Height\":\"160\",\"FileSize\":\"2608\"}},{\"__metadata\":{\"uri\":\"https://api.datamarket.azure.com/Data.ashx/Bing/Search/Image?Query=\u0027林志玲\u0027&$skip=3&$top=1\",\"type\":\"ImageResult\"},\"ID\":\"1ece9e75-71fa-439e-88c6-fe13c28e7ac6\",\"Title\":\"林志玲 遠東國際飯店\",\"MediaUrl\":\"http://photos.orzzso.com/img/photo/1/835-2.jpg\",\"SourceUrl\":\"http://photos.orzzso.com/image/1/1/835\",\"DisplayUrl\":\"photos.orzzso.com/image/1/1/835\",\"Width\":\"600\",\"Height\":\"900\",\"FileSize\":\"120002\",\"ContentType\":\"image/jpeg\",\"Thumbnail\":{\"__metadata\":{\"type\":\"Bing.Thumbnail\"},\"MediaUrl\":\"http://ts3.mm.bing.net/images/thumbnail.aspx?q=4937318944801750&id=ebbb86b8006674af1d82fbbc52099fcc\",\"ContentType\":\"image/jpg\",\"Width\":\"106\",\"Height\":\"160\",\"FileSize\":\"2488\"}},{\"__metadata\":{\"uri\":\"https://api.datamarket.azure.com/Data.ashx/Bing/Search/Image?Query=\u0027林志玲\u0027&$skip=4&$top=1\",\"type\":\"ImageResult\"},\"ID\":\"f09f57cc-73bf-4c95-8693-0201051c2471\",\"Title\":\"林志玲 遠東國際飯店 - 林志玲 遠東國際飯店 - 美女 ...\",\"MediaUrl\":\"http://www.orzzm.com/img/1/516-2.jpg\",\"SourceUrl\":\"http://orzzm.com/image/1/516\",\"DisplayUrl\":\"orzzm.com/image/1/516\",\"Width\":\"600\",\"Height\":\"900\",\"FileSize\":\"135797\",\"ContentType\":\"image/jpeg\",\"Thumbnail\":{\"__metadata\":{\"type\":\"Bing.Thumbnail\"},\"MediaUrl\":\"http://ts2.mm.bing.net/images/thumbnail.aspx?q=4557502140514313&id=c73ca99a4d658b617c8392040f0abe24\",\"ContentType\":\"image/jpg\",\"Width\":\"106\",\"Height\":\"160\",\"FileSize\":\"2755\"}},{\"__metadata\":{\"uri\":\"https://api.datamarket.azure.com/Data.ashx/Bing/Search/Image?Query=\u0027林志玲\u0027&$skip=5&$top=1\",\"type\":\"ImageResult\"},\"ID\":\"c56dbc73-0fe9-470f-9954-8f927e00f12f\",\"Title\":\"林志玲趙本三「合作」粉絲「熱捧」林志玲__娛樂 ...\",\"MediaUrl\":\"http://imgcache.chinayes.com/cnews/20120404/201204041117323586934.jpg\",\"SourceUrl\":\"http://tw.twent.chinayes.com/Content/20120404/kfjow1ex2qg1k_3.shtml\",\"DisplayUrl\":\"tw.twent.chinayes.com/Content/20120404/kfjow1ex2qg1k_3.shtml\",\"Width\":\"440\",\"Height\":\"473\",\"FileSize\":\"81984\",\"ContentType\":\"image/jpeg\",\"Thumbnail\":{\"__metadata\":{\"type\":\"Bing.Thumbnail\"},\"MediaUrl\":\"http://ts1.mm.bing.net/images/thumbnail.aspx?q=4894614097953600&id=8a2112530f13f747b811475accb54103\",\"ContentType\":\"image/jpg\",\"Width\":\"148\",\"Height\":\"160\",\"FileSize\":\"3993\"}},{\"__metadata\":{\"uri\":\"https://api.datamarket.azure.com/Data.ashx/Bing/Search/Image?Query=\u0027林志玲\u0027&$skip=6&$top=1\",\"type\":\"ImageResult\"},\"ID\":\"8fcae1ae-2a3c-47e1-aca6-fdcf2d9a7c2b\",\"Title\":\"林志玲 - 香港網絡大典\",\"MediaUrl\":\"http://images.wikia.com/evchk/images/1/15/%E6%9E%97%E5%BF%97%E7%8E%B2%E6%B1%BA%E6%88%B0%E9%83%AD%E5%8F%B0%E9%8A%98.jpg\",\"SourceUrl\":\"http://evchk.wikia.com/wiki/%E6%9E%97%E5%BF%97%E7%8E%B2\",\"DisplayUrl\":\"evchk.wikia.com/wiki/林志玲\",\"Width\":\"677\",\"Height\":\"940\",\"FileSize\":\"162864\",\"ContentType\":\"image/jpeg\",\"Thumbnail\":{\"__metadata\":{\"type\":\"Bing.Thumbnail\"},\"MediaUrl\":\"http://ts2.mm.bing.net/images/thumbnail.aspx?q=4761775067300805&id=3feb51a5bc64bd8865f79dc680354cee\",\"ContentType\":\"image/jpg\",\"Width\":\"115\",\"Height\":\"160\",\"FileSize\":\"2625\"}},{\"__metadata\":{\"uri\":\"https://api.datamarket.azure.com/Data.ashx/Bing/Search/Image?Query=\u0027林志玲\u0027&$skip=7&$top=1\",\"type\":\"ImageResult\"},\"ID\":\"df86713d-7fc5-4481-abb2-4335b9901f5e\",\"Title\":\"林志玲墜馬因禍得福 真胸假胸力挺人氣_星島環球網 ...\",\"MediaUrl\":\"http://www.stnn.cc:82/feitures/top10/ent/200512/W020051226376444413083.jpg\",\"SourceUrl\":\"http://www.stnn.cc:82/feitures/top10/ent/200512/t20051226_104600.html\",\"DisplayUrl\":\"www.stnn.cc:82/feitures/top10/ent/200512/t20051226_104600.html\",\"Width\":\"450\",\"Height\":\"426\",\"FileSize\":\"61568\",\"ContentType\":\"image/jpeg\",\"Thumbnail\":{\"__metadata\":{\"type\":\"Bing.Thumbnail\"},\"MediaUrl\":\"http://ts3.mm.bing.net/images/thumbnail.aspx?q=4708135242236782&id=28f90f8b4076489bd7434a9253b31f4b\",\"ContentType\":\"image/jpg\",\"Width\":\"160\",\"Height\":\"151\",\"FileSize\":\"4366\"}},{\"__metadata\":{\"uri\":\"https://api.datamarket.azure.com/Data.ashx/Bing/Search/Image?Query=\u0027林志玲\u0027&$skip=8&$top=1\",\"type\":\"ImageResult\"},\"ID\":\"2d642ade-5b0b-4ec5-9b63-aa0937347423\",\"Title\":\"林志玲寫真集最新精選[24P] @ 正妹寫真集 :: 痞客邦 ...\",\"MediaUrl\":\"http://pic.pimg.tw/vivian88job/93a81132afdaa798f02ee77a78d6569c.jpg\",\"SourceUrl\":\"http://vivian88job.pixnet.net/blog/post/10092256-%e6%9e%97%e5%bf%97%e7%8e%b2%e5%af%ab%e7%9c%9f%e9%9b%86%e6%9c%80%e6%96%b0%e7%b2%be%e9%81%b8%5b24p%5d\",\"DisplayUrl\":\"vivian88job.pixnet.net/blog/post/10092256-林志玲寫真集最新...\",\"Width\":\"400\",\"Height\":\"600\",\"FileSize\":\"57721\",\"ContentType\":\"image/jpeg\",\"Thumbnail\":{\"__metadata\":{\"type\":\"Bing.Thumbnail\"},\"MediaUrl\":\"http://ts2.mm.bing.net/images/thumbnail.aspx?q=4609862080726529&id=c0ddc8e3a5bdbcc1d00f2c97955fa9df\",\"ContentType\":\"image/jpg\",\"Width\":\"106\",\"Height\":\"160\",\"FileSize\":\"3440\"}},{\"__metadata\":{\"uri\":\"https://api.datamarket.azure.com/Data.ashx/Bing/Search/Image?Query=\u0027林志玲\u0027&$skip=9&$top=1\",\"type\":\"ImageResult\"},\"ID\":\"5c730f64-1f14-44ad-a077-af38cf18c634\",\"Title\":\"林志玲 - wiki 互動維客 - -生活格子- 口碑整形論壇 ...\",\"MediaUrl\":\"http://a2.att.hudong.com/67/59/01300000201862121567590269867.jpg\",\"SourceUrl\":\"http://bbs.105life.com/doc.php?action=viewhis&docid=1527&hisid=21256\",\"DisplayUrl\":\"bbs.105life.com/doc.php?action=viewhis&docid=1527&hisid=21256\",\"Width\":\"384\",\"Height\":\"497\",\"FileSize\":\"60045\",\"ContentType\":\"image/jpeg\",\"Thumbnail\":{\"__metadata\":{\"type\":\"Bing.Thumbnail\"},\"MediaUrl\":\"http://ts4.mm.bing.net/images/thumbnail.aspx?q=4704046417641859&id=009ed5202e5ee55bb7e9c32860e12522\",\"ContentType\":\"image/jpg\",\"Width\":\"123\",\"Height\":\"160\",\"FileSize\":\"4194\"}}],\"__next\":\"https://api.datamarket.azure.com/Data.ashx/Bing/Search/Image?Query=\u0027%E6%9E%97%E5%BF%97%E7%8E%B2\u0027&$skip=10&$top=10\"}}";
		// List<ImageDO> imageList = BImageSearch.response2Image(response);
		// System.out.println(imageList);
	}
}
